<?php
namespace custom;

class Dense
{

    const STR_LEN = 16;
    protected $cipher = 'AES-128-CBC';
    public function setCipher($cipher = 'AES-128-CBC') {
        $this->cipher = $cipher;
    }

    /**
     * 加密
     * @param $buff
     * @param string $key
     * @return string
     */
    public function encrypt($buff,$key='') {
        $iv = get_nonce_str(self::STR_LEN);
        !is_string($buff) && $buff = json_encode($buff);
        $encData = openssl_encrypt($buff, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
        $encData=bin2hex($encData);
        return bin2hex($iv . $encData);
    }

    /**
     * 解密
     * @param $buff
     * @param $key
     * @return string
     */
    public function decrypt($buff,$key='') {
        $buff=hex2bin($buff);
        $encData = substr($buff, 16);
        $encData=hex2bin($encData);
        $iv = substr($buff, 0, 16);
        $data = openssl_decrypt($encData, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
        return $data;
    }

    protected function getKeyIv($str) {
        $key = $iv = '';
        $len = self::STR_LEN / 2;
        for($i = 0; $i < $len; ++$i) {
            $k = $i * 2;
            $key .= substr($str, $k, 1);
            $iv .= substr($str, $k + 1, 1);
        }
        return [$key, $iv];
    }


}